﻿using System.Text;
using System.Web.Mvc;
using System.IO;

namespace $myprojectname$.Infrastructure.Extensions
{
    /// <summary>
    /// Extensions methods for the controllers.
    /// </summary>
    public static class Controllers
    {
        /// <summary>
        /// It renders a view to a string.
        /// </summary>
        /// <param name="controller">The current controller.</param>
        /// <param name="viewName">the view name.</param>
        /// <param name="model">The model.</param>
        /// <returns>The view as string.</returns>
        public static string RenderViewToString(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }

            controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, string.Empty);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

    }
}
